package com.tp;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EditTrip extends CustomWindow implements OnClickListener,
		OnItemClickListener {
	static int id_TripDetail, id_TripDetailRes, id_TripDetailEvent;
	int id_TripHotel;
	static int day;
	String des;
	static int ini = 1;
	static int select_hotel = 0, select_res = 0, select_event = 0;
	static String items[] = { "Hotel", "Restaurant", "Event" };

	static EditText startDate;
	static String date;
	static String name;
	Button setDate;
	static EditText tripName;
	Button next, submit;
	TextView _day;
	EditText _des;
	int id_Hotel;
	int id_Res, id_Event;
	static String time;
	static String hotelDes;
	static int id_Trip;
	static int duration;
	DateFormat fmtDateAndTime = DateFormat.getDateTimeInstance();
	Calendar dateAndTime = Calendar.getInstance();
	DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			if (date == null) {
				dateAndTime.set(Calendar.YEAR, year);
				dateAndTime.set(Calendar.MONTH, monthOfYear);
				dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				updateLabel();
				date = startDate.getText().toString();
			}
		}
	};

	private void updateLabel() {
		if (date == null) {
			startDate.setText("" + dateAndTime.get(Calendar.YEAR) + "-"
					+ (dateAndTime.get(Calendar.MONTH) + 1) + "-"
					+ dateAndTime.get(Calendar.DAY_OF_MONTH));

		} else
			startDate.setText(date);
		// start_btn.setText(fmtDateAndTime.format(dateAndTime.DATE));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_header);
		this.icon.setImageResource(R.drawable.modify);
		this.title.setText("Cập nhật hành trình");
		Hotel.flag = 2;
		Restaurant.flag = 2;
		Event.flag = 2;
		_day = (TextView) findViewById(R.id.day);
		_day.setText("Ngày " + day);
		_des = (EditText) findViewById(R.id.tripDes);
		startDate = (EditText) findViewById(R.id.create_start_date);
		tripName = (EditText) findViewById(R.id.create_name);
		setDate = (Button) findViewById(R.id.setDate);
		if (hotelDes != null)
			_des.setText(hotelDes);

		if (name != null)
			tripName.setText(name);
		if (date != null)
			startDate.setText(date);
		if (ini == 1) {
			getTrip();
			getTripDetailHotel();

		}
		ListView list_trip = (ListView) findViewById(R.id.trip_list);
		list_trip.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, items));
		list_trip.setOnItemClickListener(this);
		list_trip.setScrollingCacheEnabled(true);

		setDate.setOnClickListener(this);
		updateLabel();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.nextday:
			if (day > duration)
				addHotel();
			else {
				if (select_hotel == 1) {
					updateHotel(); // add hotel, res
					select_hotel = 0;
				}
				if (select_res == 1) {
					deleteResEvent(2);
					addRes();
					select_res = 0;
				}
				if (select_event == 1) {
					deleteResEvent(3);
					select_event = 0;
					addEvent();
				}
			}
			day++;
			hotelDes = "";
			items[0] = "Khách sạn";
			items[1] = "Nhà hàng";
			items[2] = "Sự kiện";
			ini = 1;
			startActivity(new Intent(this, EditTrip.class));
			break;
		case R.id.submit:
			updateTripTime(id_Trip, startDate.getText().toString());
			if (day > duration) {
				addHotel();
				updateTrip(id_Trip, day);
			} else {
				if (select_hotel == 1) {
					updateHotel(); // add hotel, res
					select_hotel = 0;
				}
				if (select_res == 1) {
					deleteResEvent(2);
					addRes();
					select_res = 0;
				}
				if (select_event == 1) {
					deleteResEvent(3);
					select_event = 0;
					addEvent();
				}
			}
			ini = 1;
			day = 1;
			name = "";
			hotelDes = "";
			items[0] = "Khách sạn";
			items[1] = "Nhà hàng";
			items[2] = "Sự kiện";
			startActivity(new Intent(this, ListTrip.class));
			break;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.setDate:
			name = tripName.getText().toString();
			// Create.tripName.setText(Create.tripName.getText().toString());
			date = null;
			new DatePickerDialog(EditTrip.this, d,
					dateAndTime.get(Calendar.YEAR),
					dateAndTime.get(Calendar.MONTH),
					dateAndTime.get(Calendar.DAY_OF_MONTH)).show();
			updateLabel();
			/*
			 * if(date !=null) { startDate.setText("" +
			 * dateAndTime.get(Calendar.YEAR) + "-" +
			 * (dateAndTime.get(Calendar.MONTH) + 1) + "-" +
			 * dateAndTime.get(Calendar.DAY_OF_MONTH)); date =
			 * startDate.getText().toString(); } updateLabel();
			 */tripName.setText(name);

			break;

		}
	}

	private void updateTripTime(int id_Trip2, String string) {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip2)));
		postParameters.add(new BasicNameValuePair("startDate", string));
		// String response = null;
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/updateTripTime", postParameters);
			/*
			 * String res = response.toString(); res = res.replaceAll("\\s+",
			 * "");
			 */

		} catch (Exception e) {

		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub

		name = tripName.getText().toString();
		hotelDes = _des.getText().toString();

		if (position == 0) {
			select_hotel = 1;
			items[0] = "Khách sạn";
			startActivity(new Intent(this, Hotel.class));
		} else if (position == 1) {
			select_res = 1;
			items[1] = "Nhà hàng";
			startActivity(new Intent(this, Restaurant.class));
		} else if (position == 2) {
			select_event = 1;
			items[2] = "Sự kiện";
			startActivity(new Intent(this, Event.class));
		}

	}

	private void getTrip() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		// ArrayList<String> r = new ArrayList<String>();
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));

		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripById", postParameters);

			if (result != "") {

				jArray = new JSONArray(result);
				// jArr = jArray;
				for (i = 0; i < jArray.length(); i++) {
					json_data = jArray.getJSONObject(i);
					name = json_data.getString("name").toString();
					tripName.setText(name);
					date = json_data.getString("dateStart");
					startDate.setText(date);
					duration = json_data.getInt("duration");
					// r.add(json_data.getString("name") + ", Ngày "
					// + json_data.getString("dateStart"));
				}
			}
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// return r;

	private void getTripDetailHotel() {

		JSONArray jArray;
		JSONObject json_data = null;
		int i;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters
				.add(new BasicNameValuePair("day", Integer.toString(day)));
		String result = null;
		String hotel = "Hotel";
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailHotel", postParameters);

			jArray = new JSONArray(result);
			// jArr = jArray;
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetail = json_data.getInt("id_TripDetail");
				day = json_data.getInt("day");
				id_Hotel = json_data.getInt("id_Hotel");

				des = json_data.getString("description");
				hotel += "\n" + getObject(id_Hotel);
				// array.add(new Item(R.drawable.hotel, getObject(id_Hotel),
				// id_Hotel, 1));
				if (id_TripDetail > 0) {
					getTripDetailRes();
					getTripDetailEvent();
				}

			}
			items[0] = hotel;
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getTripDetailRes() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		String result = null;
		String res = "Restaurant";
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailRes", postParameters);

				jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetailRes = json_data.getInt("id_TripDetailRes");
				time = json_data.getString("time");
				id_Res = json_data.getInt("id_Res");
				res += "\n" + getObject(id_Res);

				// array.add(new Item(R.drawable.restaurant, getObject(id_Res),
				// id_Res, 2));
			}
			items[1] = res;

		} catch (JSONException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getTripDetailEvent() {
		JSONArray jArray;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		String result = null;
		String event = "Event";
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/getTripDetailEvent", postParameters);

				jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				id_TripDetailEvent = json_data.getInt("id_TripDetailEvent");
				time = json_data.getString("time");
				id_Event = json_data.getInt("id_Event");
				event += "\n" + getObject(id_Event);

			}
			items[2] = event;

		} catch (JSONException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getObject(int id_Obj) {
		// END Convert response to string
		JSONArray jArray;
		String name = null;
		JSONObject json_data = null;
		int i;

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id_Obj)));

		String result = null;
		try {
			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/getObjectById", postParameters);

				jArray = new JSONArray(result);
			for (i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				// Log.d("A", json_data.getString("name"));
				name = json_data.getString("name");
			}
			// return r;
		} catch (JSONException e1) {

		} catch (ParseException e1) {

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return name;

	}

	private void updateHotel() {
		String sub[] = items[0].split("\n");// tach hotel va luu vao mang sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			for (int j = 0; j < Hotel.jArr.length(); j++) {
				try {
					JSONObject json_data = Hotel.jArr.getJSONObject(j); // lay
																		// tung
																		// hotel
																		// trong
																		// DB
					String name2 = json_data.getString("name");
					if (sub[i].equals(name2)) { // so sanh hotel trong DB vs
												// hotel trong sub[]
						id_Hotel = json_data.getInt("id_Obj");
						// get id trip detail = id_TripHotel
						sendTripDetailHotel(id_TripDetail, id_Hotel, hotelDes);
						// add res cho moi trip detail

					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Toast.makeText(this, "EXception addHotel",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private void addHotel() {
		String sub[] = items[0].split("\n");// tach hotel va luu vao mang sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			for (int j = 0; j < Hotel.jArr.length(); j++) {
				try {
					JSONObject json_data = Hotel.jArr.getJSONObject(j); // lay
																		// tung
																		// hotel
																		// trong
																		// DB
					String name2 = json_data.getString("name");
					if (sub[i].equals(name2)) { // so sanh hotel trong DB vs
												// hotel trong sub[]
						id_Hotel = json_data.getInt("id_Obj");
						// get id trip detail = id_TripHotel
						id_TripDetail = sendTripDetailHotel2(id_Trip, day,
								id_Hotel, hotelDes);
						// add res cho moi trip detail

						addRes();
						addEvent();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Toast.makeText(this, "EXception addHotel",
							Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	private int sendTripDetailHotel2(int id_Trip, int day, int id_Hotel,
			String des) {
		// TODO Auto-generated method stub
		int id_TripDetailHotel = 0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters
				.add(new BasicNameValuePair("day", Integer.toString(day)));
		postParameters.add(new BasicNameValuePair("id_Hotel", Integer
				.toString(id_Hotel)));
		postParameters.add(new BasicNameValuePair("description", des));

		// String valid = "1";
		String response = null;
		try {
			response = CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/addTripDetailHotel", postParameters);
			String res = response.toString();
			res = res.replaceAll("\\s+", "");
			// error.setText(res);
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Insert hotel successful",
						Toast.LENGTH_SHORT).show();
				id_TripDetailHotel = Integer.parseInt(res);
				startActivity(new Intent(this, Main.class));

			} else
				Toast.makeText(this, "Sorry!! Insert hotel not successful",
						Toast.LENGTH_SHORT).show();

		} catch (Exception e) {

		}
		return id_TripDetailHotel;
	}

	private void addRes() {
		// TODO Auto-generated method stub
		String sub[] = items[1].split("\n"); // tach "res + time" tuong ung luu
												// vao sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			String res[] = sub[i].split(" luc "); // tach res va time luu vao
													// res[], res[0] = res,
													// res[1] = time
			for (int j = 0; j < Restaurant.jArr.length(); j++) {
				try {
					JSONObject json_data = Restaurant.jArr.getJSONObject(j);
					String name2 = json_data.getString("name");
					if (res[0].equals(name2)) {
						id_Res = json_data.getInt("id_Obj");
						sendTripDetailResEvent(id_TripDetail, id_Res, res[1], 2);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Toast.makeText(this, "EXception addRes", Toast.LENGTH_SHORT)
							.show();
				}
			}
		}

	}

	private void addEvent() {
		// TODO Auto-generated method stub
		String sub[] = items[2].split("\n"); // tach "res + time" tuong ung luu
												// vao sub[]
		for (int i = 1; i < sub.length; i++) {
			Log.v("SUB", sub[i]);
			String event[] = sub[i].split(" luc "); // tach res va time luu vao
													// res[], res[0] = res,
													// res[1] = time
			for (int j = 0; j < Event.jArr.length(); j++) {
				try {
					JSONObject json_data = Event.jArr.getJSONObject(j);
					String name2 = json_data.getString("name");
					if (event[0].equals(name2)) {
						id_Event = json_data.getInt("id_Obj");
						sendTripDetailResEvent(id_TripDetail, id_Event,
								event[1], 3);
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					Toast.makeText(this, "EXception addEvent",
							Toast.LENGTH_SHORT).show();
				}
			}
		}

	}

	private void sendTripDetailResEvent(int id, int id_Obj, String time,
			int id_Type) {
		// TODO Auto-generated method stub

		// int id_TripDetailHotel = 0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id)));
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id_Obj)));
		postParameters.add(new BasicNameValuePair("time", time));
		postParameters.add(new BasicNameValuePair("id_Type", Integer
				.toString(id_Type)));

		// String valid = "1";
		// String response = null;
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/updateTripDetailResEvent",
					postParameters);

		} catch (Exception e) {
			Log.v("sendTripDetailResEvent", e.toString());
		}
		// return id_TripDetailHotel;
	}


	private void sendTripDetailHotel(int id_TripDetail, int id_Hotel, String des) {
		// TODO Auto-generated method stub
		// int id_TripDetailHotel = 0;
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		postParameters.add(new BasicNameValuePair("id_Hotel", Integer
				.toString(id_Hotel)));

		postParameters.add(new BasicNameValuePair("description", des));

		// String valid = "1";
		// String response = null;
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/updateTripDetailHotel", postParameters);

		} catch (Exception e) {
			Log.v("sendTripDetailHotel", e.toString());

		}
		// return id_TripDetailHotel;
	}

	private void deleteResEvent(int type) {
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_TripDetail", Integer
				.toString(id_TripDetail)));
		postParameters.add(new BasicNameValuePair("type", Integer
				.toString(type)));
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/deleteTripDetail", postParameters);

		} catch (Exception e) {
			Log.v("deleteResEvent", e.toString());

		}
	}

	private void updateTrip(int id_Trip, int duration) {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_Trip", Integer
				.toString(id_Trip)));
		postParameters.add(new BasicNameValuePair("duration", Integer
				.toString(duration)));
		// String response = null;
		try {
			CustomHttpClient.executeHttpPost(Constant.host
					+ "/TripController/updateTrip", postParameters);
			/*
			 * String res = response.toString(); res = res.replaceAll("\\s+",
			 * "");
			 */

		} catch (Exception e) {

		}

	}
}
